package com.leyou.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leyou.client.SpecClient;
import com.leyou.client.SpuClient;
import com.leyou.item.Goods;
import com.leyou.pojo.*;
import com.leyou.repository.GoodsRepository;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodService {

    @Autowired
    private SpecClient specClient;
    @Autowired
    private SpuClient spuClient;
    @Autowired
    private GoodsRepository goodsRepository;

    private static final ObjectMapper MAPPER = new ObjectMapper();


    public Goods convert(SpuVo spuVo) throws Exception {
        Goods goods = new Goods();

        //把查询到的spu转换到goods实体
        //可以用goods elasticsearch- repository导入索引库

        //基础数据
        goods.setId(spuVo.getId());
        goods.setSubTitle(spuVo.getSubTitle());
        goods.setBrandId(spuVo.getBrandId());
        goods.setCid1(spuVo.getCid1());
        goods.setCid2(spuVo.getCid2());
        goods.setCid3(spuVo.getCid3());
        goods.setCreateTime(spuVo.getCreateTime());


        //all 存放的是可搜索的词条 标题+分类+品牌    手机 通讯 手机 通讯 华为
        goods.setAll(spuVo.getTitle() + " " + spuVo.getCname().replace("/", " ") + " " + spuVo.getBname());

        //goods.setAll(spuVo.getTitle().concat(" ").concat(spuVo.getCname().replace("/"," ")).concat(" ").concat(spuVo.getBname()));

        //复杂数据
        //根据spuid查询sku集合
        List<Sku> skuList = spuClient.list(spuVo.getId());

        //把sku价钱封装到 goods price数组中

        List<Integer> price = new ArrayList<>();
        for (Sku sku : skuList) {
            price.add(sku.getPrice());
        }
        goods.setPrice(price);
        goods.setSkus(MAPPER.writeValueAsString(skuList));


        //存放map数组  规格参数
        Map<String, Object> specs = new HashMap<>();


        //根据三级分类id和可搜索条件查询规格参数spec_param
        List<Spec_param> specParamList = specClient.getparamsq(spuVo.getCid3());

        //根据spuid查询spudetail1
        SpuDetail spuDetail = spuClient.detail(spuVo.getId());
        // 获取通用的规格参数
        //把json串转为map
        Map<Long, Object> genericSpecMap = MAPPER.readValue(spuDetail.getGenericSpec(), new TypeReference<Map<Long, Object>>() {
        });
        // 获取特殊的规格参数
        Map<Long, List<Object>> specialSpecMap = MAPPER.readValue(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<Object>>>() {
        });
        // 定义map接收{规格参数名，规格参数值}
        Map<String, Object> paramMap = new HashMap<>();
        specParamList.forEach(param -> {
            // 判断是否通用规格参数
            if (param.getGeneric()) {
                // 获取通用规格参数值
                System.out.println("param:" + param);
                String value = genericSpecMap.get(param.getId()) == null ? "" : genericSpecMap.get(param.getId()).toString();
                if (!value.equals("")) {
                    // 判断是否是数值类型
                    if (param.getNumeric()) {
                        // 如果是数值的话，判断该数值落在那个区间
                        value = chooseSegment(value, param);
                    }
                    // 把参数名和值放入结果集中
                    paramMap.put(param.getName(), value);
                }

            } else {
                paramMap.put(param.getName(), specialSpecMap.get(param.getId()));
            }
        });
        goods.setSpecs(paramMap);
        return goods;
    }

        private String chooseSegment (String value, Spec_param p){
            double val = NumberUtils.toDouble(value);
            String result = "其它";
            // 保存数值段
            for (String segment : p.getSegments().split(",")) {
                String[] segs = segment.split("-");
                // 获取数值范围
                double begin = NumberUtils.toDouble(segs[0]);
                double end = Double.MAX_VALUE;
                if (segs.length == 2) {
                    end = NumberUtils.toDouble(segs[1]);
                }
                // 判断是否在范围内
                if (val >= begin && val < end) {
                    if (segs.length == 1) {
                        result = segs[0] + p.getUnit() + "以上";
                    } else if (begin == 0) {
                        result = segs[1] + p.getUnit() + "以下";
                    } else {
                        result = segment + p.getUnit();
                    }
                    break;
                }
            }
            return result;
        }

        /**
         * rabbitmq 监听消息修改es数据
         * @param spuId
         */
    public void editEsData(Integer spuId) throws Exception {

        //1：根据spuid查询spu
        Spu spu = spuClient.findSpuBuId(spuId);
        SpuVo spuVo = new SpuVo();
        BeanUtils.copyProperties(spu,spuVo);
        //2：spu转换成googs
        Goods goods = this.convert(spuVo);

        //3：持久化到es
        goodsRepository.save(goods);
    }

        public void deleteEsData (Long spuId){

            goodsRepository.deleteById(spuId);

        }
    }

